export default {
  namespaced: true,
  state: {
    goodsList: uni.getStorageSync('cart') || []
  },
  getters: {
    getTotal (state) {
      let total = 0
      state.goodsList.forEach(item => {
        total += item.goods_number
      })

      return total
    },
    // 返回一个商品列表，用getters有缓存
    getCartList(state){
      return state.goodsList
    },
    // 获取选中的商品总数
    getSelectTotal(state){
      let total = 0
      state.goodsList.forEach(item => {
        if(item.goods_state){
          total+=item.goods_number
        }
      })
      return total
    },
    // 选中的商品总金额
    getSelectPrice(state){
      let Price = 0
      state.goodsList.forEach(item => {
        if(item.goods_state){
          Price+=item.goods_number *item.goods_price
        }
      })
      return Price
    },
    // 购物车是否全部选中
    isAllSelect(state){
      let isAllSelect=true
      state.goodsList.forEach(item=>{
        if(!item.goods_state){
          isAllSelect=false
        }
      })
      return isAllSelect
    }
  },
  mutations: {
    addToCart (state, goods) {
      //   console.log('---addToCart----', goods)
      const findGoods = state.goodsList.find(
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        findGoods.goods_number += goods.goods_number
      } else {
        state.goodsList.push(goods)
      }

      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 更改购物车中商品的状态
    changeGoodsState(state,goods){
      console.log(goods);
      const findGoods = state.goodsList.find(
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        findGoods.goods_state = goods.goods_state
      } 
      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 更改购物车的商品的数量
    changeGoodsNumber(state,goods){
      console.log(goods);
      const findGoods = state.goodsList.find(
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        findGoods.goods_number = goods.goods_number
      } 
      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 根据id删除购物车商品
    deleteGoodsById(state,goods_id){
      // 查找数组中相对应的id
      const findIndex=state.goodsList.findIndex(item=>item.goods_id===goods_id)
      if(findIndex>1){
        state.goodsList.splice(findIndex,1)
      }
       // 保存到本地
       uni.setStorageSync('cart', state.goodsList)
    },
    // 全选&反选
    selectOrNotSelect(state,goods_state){
      state.goodsList.forEach(item=>{
        item.goods_state=goods_state
      })
      // 保存到本地
      uni.setStorageSync('cart', state.goodsList)
    }
  }
}
